﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.ServiceModel;
using OrbitOne.CRMLyncInfoDashboard.CRM.Organization;

namespace OrbitOne.CRMLyncInfoDashboard.CRM.WCF
{
    [Export(typeof(ICrmGlobalMetadataProvider))]
    public class CrmGlobalMetadataProvider : ICrmGlobalMetadataProvider
    {
        private readonly IWCFHelper m_wcfHelper;

        [ImportingConstructor]
        public CrmGlobalMetadataProvider(IWCFHelper wcfHelper)
        {
            m_wcfHelper = wcfHelper;
        }

        public void RetrieveEntities(Uri serverUrl, IDataCollection viewModel)
         {
             try
             {
                 var client = (OrganizationServiceClient)m_wcfHelper.GetConnection(serverUrl);
                 var request = new OrganizationRequest
                                   {
                                       RequestName = "RetrieveAllEntities",
                                       Parameters = new ParameterCollection
                                                        {
                                                            new OrbitOne.CRMLyncInfoDashboard.CRM.WCF.KeyValuePair<string, object>("EntityFilters", EntityFilters.Entity),
                                                            new OrbitOne.CRMLyncInfoDashboard.CRM.WCF.KeyValuePair<string, object>("RetrieveAsIfPublished", true)
                                                        }
                                   };
                 client.ExecuteCompleted += (o, response) =>
                                                {
                                                    viewModel.EntityMetadata = GetEntitiesMetadataResult(response, viewModel);
                                                };
                 client.ExecuteAsync(request);
             }
             catch (FaultException<OrganizationServiceFault> ex)
             {
                 throw;
             }
         }
        

        private EntityMetadata[] GetEntitiesMetadataResult(ExecuteCompletedEventArgs response, IDataCollection viewModel)
        {

            try
            {
                var data = (IList<EntityMetadata>)response.Result.Results[0].Value;
                var entities = data.OrderBy(a => a.SchemaName).ToList();
                return entities.ToArray();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}